const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//const ExtractTextPlugin = require("extract-text-webpack-plugin");
// const CopyWebpackPlugin = require('copy-webpack-plugin');
const path=require('path');
const fs=require('fs');

// 生产环境
var isProd = process.env.NODE_ENV === 'production';

function resolve(projectPath){
    return path.resolve(__dirname, projectPath);
}

// 服务端打包时用到，作用是打包时保留原来引用的模块名，如会把import 'react-router'转化成require('react-router')
// 如果不设置此externals的话，webpack会进一步深入到react-router里把其依赖的所有包都一起打包，这对于NODEJS环境是多余的
function getExternals() {
    return fs.readdirSync(path.resolve(__dirname, './node_modules'))
        .filter(filename => !filename.includes('.bin'))
        .reduce((externals, filename) => {
            externals[filename] = `commonjs ${filename}`;
            return externals
        }, {})
}

var plugins=[
    new webpack.optimize.CommonsChunkPlugin({name:'vendor'}),
    new webpack.optimize.CommonsChunkPlugin({name:'app', children:true, async:true, minChunks:2}),
    //new ExtractTextPlugin({
    //    filename: isProd ? '[name].[chunkhash:8].css' : '[name].css'
    //}),
    new HtmlWebpackPlugin({
        title:'设备管理',
        minify: {
            caseSensitive: false,             //是否大小写敏感
            collapseBooleanAttributes: true, //是否简写boolean格式的属性如：disabled="disabled" 简写为disabled
            collapseWhitespace: true         //是否去除空格
        },
        // favicon:'./src/img/favicon.png',
        template:'./src/index.html',
        filename:'./index.html' //结合output.path
    }),
    // new CopyWebpackPlugin([
    //     {
    //         from:resolve('src/vendor')
    //     }
    // ]),
    new webpack.ProvidePlugin({
        React:'react'
    }),
    new webpack.HotModuleReplacementPlugin()
];
if(isProd){
    plugins.push(new webpack.DefinePlugin({ // <-- 减少 React 大小的关键
        'process.env': {
            'NODE_ENV': JSON.stringify('production')
        }
    }));
    plugins.push(new webpack.optimize.UglifyJsPlugin());
    //合并块
    plugins.push(new webpack.optimize.AggressiveMergingPlugin());
}

const clientConfig={
    name:'browser',
    entry: {
        app: './src/js/index',
        vendor:[
            'react',
            'react-dom',
            'react-router',
            'react-redux',
            'redux',
            'redux-thunk'
        ]
    },
    output: {
        //publicPath:isProd ? './' : '/', //给require.ensure用；webpack-dev-server的网站名
        path: resolve('dist'), //js的发布路径
        filename: '[name].js', //固定app.js和vendor.js名称，因server render里是写死的
        chunkFilename:isProd ? '[name].chunk.[hash:8].js' : '[name].chunk.js'
    },
    // resolve: {
    //     extensions: ['.js', '.scss'],
    //     alias:{
    //         img:resolve('src/img'),
    //         sass:resolve('src/sass'),
    //         appHistory:resolve('src/js/history.js'),
    //         appStore:resolve('src/js/store.js'),
    //         appAction:resolve('src/js/action.js'),
    //         components:resolve('src/js/components'),
    //         pages:resolve('src/js/pages'),
    //         hoc:resolve('src/js/hoc'),
    //         utils:resolve('src/js/utils'),
    //         config:resolve('src/js/config')
    //     }
    // },
    module: {
        loaders: [
            // {test: /\.(otf|eot|svg|ttf|woff|woff2)\??.*$/, use:'url-loader?limit=50000&name=[hash:8].[ext]'},
            // {test: /\.css$/, use:['style-loader', 'css-loader?minimize']},
            //{test: /\.scss$/, use: ExtractTextPlugin.extract({
            //    fallback: 'style-loader',
            //    use: ['css-loader', 'sass-loader']
            //}), include:resolve('src/sass')},
            // {test: /\.scss$/, use: ['style-loader', 'css-loader?minimize', 'sass-loader'], include:resolve('src/sass')},
            {test: /\.js$/, use: 'babel-loader', include:resolve('src/js')},
            // {test: /\.(png|jpe?g|gif)$/,use: 'url-loader?limit=8192&name=[hash:8].[ext]' }
        ]
    },
    plugins: plugins,
    devServer:{
        host:'0.0.0.0',
        port:3003,
        //publicPath: '/',
        //contentBase: path.join(__dirname, "public"), //静态资源
        //代理
        proxy:{
            //"/api/": {
            //    target: "http://10.92.36.90:8280/cf-wx/",
            //    pathRewrite: {"^/api/" : ""}
            //},
            "/api/": {
                target: "http://119.23.205.81:8080/cf-wx/",
                pathRewrite: {"^/api/" : ""}
            }
        },
        hot: true,
        historyApiFallback: true
    }
};

const serverConfig={
    name:'server-side rendering',
    target: 'node',
    node: {
        __filename: true,
        __dirname: true
    },
    entry: {
        server:'./server/app'
    },
    output: {
        path: resolve('dist'), //js的发布路径
        filename: '[name].js'
    },
    module: {
        loaders: [
            {test: /\.js$/, use: 'babel-loader', include:[resolve('server'), resolve('src/js')]},
        ]
    },
    externals: getExternals(),
    plugins: [
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({
            compress: {warnings: false},
            comments: false
        }),
        new webpack.ProvidePlugin({
            React:'react'
        }),
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }
        })
    ],
};

if(isProd){
    module.exports=[clientConfig, serverConfig];
}else{
    module.exports=clientConfig;
}